package com.logreview.produce;

import com.logreview.ApplicationProperties;
import com.logreview.util.FileUtil;
import com.logreview.vo.LoggerVO;
import com.logreview.vo.Monitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 日志生产
 */
@SuppressWarnings("SpringJavaAutowiredMembersInspection")
public class LoggerProduce implements Runnable {
    private Logger logger = LoggerFactory.getLogger(LoggerProduce.class);
    private volatile boolean isRunning = true;
    private BlockingQueue<LoggerVO> queue;// 内存缓冲区

    @Autowired
    private ApplicationProperties applicationProperties;

    private LoggerProduce(){}

    public LoggerProduce(BlockingQueue<LoggerVO> queue){
        this.queue = queue;
    }

    public void run() {
        LoggerVO vo = new LoggerVO();

        while (isRunning){
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                logger.error("InterruptedException",e);
            }

            //从日志文件中读取一行
            String line = "";
            try {
                line = FileUtil.readline(applicationProperties.getLoggerPath());
            } catch (Exception e) {
                logger.error("FileUtil.readline exception",e);
            }

            //如果没有读取到数据则不处理
            if (StringUtils.isEmpty(line)){
                continue;
            }

            //将行转换成vo
            logger.info("line={}",line);
            try{
                vo = transForm(line);
            }catch (Exception e){
                logger.error("line transform to VO failed,line={}",line,e);
                continue;//转换失败记录日志，不处理该条记录
            }


            //将vo放入队列
            try {
                boolean flag = queue.offer(vo,2,TimeUnit.SECONDS);
                if(!flag){
                    logger.error("put queue failed , queue.size={},line={}",queue.size(),line);
                }else {
                    Monitor.procedureCount.incrementAndGet();
                }
            } catch (InterruptedException e) {
                logger.error("InterruptedException",e);
            }

        }
    }

    public void stop(){
        isRunning = false;
    }

    //将Line转换成vo
    public LoggerVO transForm(String line){
        LoggerVO vo = new LoggerVO();
        String[] cols = line.split(":");
        vo.setSjc(cols[0]);
        vo.setJch(cols[1]);
        vo.setRzwyc(cols[2]);
        vo.setCxbw(cols[3]);
        vo.setFhbw(cols[4]);
        vo.setLine(line);
        return vo;
    }

}
